import ij.IJ;
import ij.ImagePlus;
import ij.ImageStack;
import ij.gui.GenericDialog;
import ij.plugin.filter.PlugInFilter;
import ij.process.ByteProcessor;
import ij.process.ImageProcessor;


public class A07_Frame_Differencing implements PlugInFilter{

	ImagePlus img1;
	double TAU = 50;
	
	@Override
	public int setup(String arg0, ImagePlus img) {
		img1 = img;
		return DOES_8G + STACK_REQUIRED + NO_CHANGES;
	}
	
	@Override
	public void run(ImageProcessor ignore) {
		if(img1 == null)
		{
			IJ.log("Kein Stack");
		}
		
		if (!getUserInput()) {
			return;
		}
		
		// Get stack1 from the source image:
		ImageStack stack1 = img1.getImageStack();
		
		ImageStack Mk = new ImageStack(stack1.getWidth(), stack1.getHeight());
		
		for(int i = 1; i < stack1.getSize(); i++)
		{
			ImageProcessor ip = new ByteProcessor(stack1.getWidth(), stack1.getHeight());
			ImageProcessor ik = stack1.getProcessor(i);
			ImageProcessor ik1 = stack1.getProcessor((i+1));
			
			for(int u = 0; u < ik.getWidth(); u++)
			{
				for(int v = 0; v < ik.getHeight(); v++)
				{
					if(Math.abs(ik1.getPixel(u, v) - ik.getPixel(u, v)) > TAU)
					{
						ip.putPixel(u, v, 255);
					} else {
						ip.putPixel(u, v, 0);
					}
				}
			}
			Mk.addSlice(ip);
		}
		
		// Display stack2:
		(new ImagePlus("Frame Differenceing", Mk)).show();
	}

	private boolean getUserInput() {
		GenericDialog gd = new GenericDialog("Select threshold");
		gd.addNumericField("Tau", TAU, 0);
		gd.showDialog();
		if(gd.wasCanceled())
		{
			return false;
		}
		TAU = gd.getNextNumber();
		if(TAU < 0)
		{
			TAU = Math.abs(TAU);
		}
		return true;
	}

	

}
